package com.cn.icss.plugins;

import com.jfinal.plugin.redis.serializer.FstSerializer;
import com.jfinal.plugin.redis.serializer.ISerializer;

import java.util.HashSet;
import java.util.Set;

/**
 * @中软华腾软件系统有限公司,未经授权不得擅自传播
 * @类描述:
 * @类名称:MyFstSerializer
 * @作者: Administrator
 * @编辑时间: 2020/04/21 12:31
 * @版本: 1.0
 */
public class MyFstSerializer implements ISerializer {
    public static final ISerializer me = new MyFstSerializer();
    private ISerializer subject = FstSerializer.me;

    private static final Set NOT_SERIALIZER_SET = new HashSet() {
        private static final long serialVersionUID = 2303504492407898281L;
        {
            add(Integer.class);
            add(Integer.TYPE);
            add(Long.class);
            add(Long.TYPE);
            add(Float.class);
            add(Float.TYPE);
            add(Double.class);
            add(Double.TYPE);
        }
    };

    @Override
    public byte[] keyToBytes(String key) {
        return FstSerializer.me.keyToBytes(key);
    }

    @Override
    public String keyFromBytes(byte[] bytes) {
        return subject.keyFromBytes(bytes);
    }

    @Override
    public byte[] fieldToBytes(Object field) {
        return valueToBytes(field);
    }

    @Override
    public Object fieldFromBytes(byte[] bytes) {
        return valueFromBytes(bytes);
    }

    @Override
    public byte[] valueToBytes(Object value) {
        if (NOT_SERIALIZER_SET.contains(value.getClass())) {
            // 如果在非序列化的名单中，就利用key值的这种不需要序列化的
            return keyToBytes(String.valueOf(value));
        }
        return subject.valueToBytes(value);
    }

    /**
     * 反序列化,利用FstSerializer解析,出错则利用keyFromBytes解析
     * @param bytes
     * @return
     */
    @Override
    public Object valueFromBytes(byte[] bytes) {
        try {
            return subject.valueFromBytes(bytes);
        } catch (Exception e) {
            // 报异常就使用这种不需要反序列化的操作
            return keyFromBytes(bytes);
        }
    }
}
